package com.t3go.t3_map.utils;


import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.shareware.common.ApplicationKt;
import com.shareware.common.utils.LogExtKt;
import com.t3go.passenger.base.entity.AddressEntity;
import com.t3go.passenger.base.entity.PersonalPointInfoEntity;
import com.t3go.passenger.base.entity.ReplaceMsgEntity;
import com.t3go.passenger.base.utils.AddressFilterUtils;
import com.t3go.passenger.base.utils.JsonUtils;
import com.t3go.passenger.base.utils.SP;
import com.t3map.api.map.entity.SubPoiItemEntity;
import com.t3map.api.map.model.T3LatLng;
import com.t3map.api.map.model.T3MarkerOptions;
import com.t3map.api.map.utils.T3MapUtils;

import java.util.List;

/**
 * 地图基础能力
 *
 * @author timpkins
 */
public final class MapFoundation {

    public static List<PersonalPointInfoEntity> personalSpotList;

    /**
     * 是否可吸附
     */
    public static boolean getPersonalSpotCache(T3LatLng t3LatLng, int adsorbRadius) {
        if (t3LatLng == null || personalSpotList == null) {
            return false;
        }
        for (PersonalPointInfoEntity entity : personalSpotList) {
            float distance = T3MapUtils.calculateLineDistance(new T3LatLng(entity.getLatitude(), entity.getLongitude()), t3LatLng);
            if (distance <= adsorbRadius && distance >= 0) {
                return true;
            }
        }
        return false;
    }


    /**
     * 计算锚点位置 anchor，相对marker图标的比例位置0-1之间（默认0.5，1.0即图标的底部居中位置）
     * 适用于添加到地图的锚点位于icon的中心
     *
     * @param bitmap 图标
     * @param anchor 锚点
     * @return 锚点数组
     */
    public static float[] calcAnchor(Bitmap bitmap, View anchor) {
        float anchorX = 0.5f;
        float anchorY = 1.0f;
        float left = 0;
        float top = 0;
        if (anchor != null) {
            anchor.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            left = anchor.getLeft() + anchor.getMeasuredWidth() / 2f;
            top = anchor.getTop() + anchor.getMeasuredHeight() / 2f;
        }
        if (bitmap != null && bitmap.getWidth() > 0 && bitmap.getHeight() > 0) {
            anchorX = left / bitmap.getWidth();
            anchorY = top / bitmap.getHeight();
        }
        return new float[]{anchorX, anchorY};
    }

    public static Bitmap convertViewToBitmap(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    /**
     * 生成 T3MarkerOptions
     *
     * @param view   要添加到地图的View
     * @param latLng 要添加到的位置
     * @return T3MarkerOptions
     */
    public static T3MarkerOptions attachMarker(View view, T3LatLng latLng) {
        return new T3MarkerOptions(latLng)
                .iconView(view)
                .draggable(false)
                .setFlat(false);
    }


    /**
     * 从原始地址信息中，格式化地址信息
     * 包括：显示地址，格式化地址，简洁地址
     *
     * @param entity
     */
    public static void formatAddressInfo(AddressEntity entity) {
        if (entity == null) {
            LogExtKt.log("TAG", "formatAddressInfo null return");
            return;
        }

        String addressTitle = entity.getAddressTitle();
        String formatAddress = entity.getAddress();
        //1.从poi获取address
        List<SubPoiItemEntity> list = entity.getSubPoiItems();
        if (list != null && !list.isEmpty()) {
            SubPoiItemEntity poiItem = list.get(0);
            if (poiItem != null) {
                if (poiItem.getTitle() != null && !poiItem.getTitle().isEmpty()) {
                    if (!poiItem.getTitle().contains("公共厕所")) {
                        addressTitle = poiItem.getTitle();
                    } else {
                        addressTitle = entity
                                .getAddress()
                                .replaceFirst(entity.getProvince(), "")
                                .replaceFirst(entity.getCity(), "");
                    }
                }
                entity.setUid(poiItem.getUuid());
            }
        }
        // 地址包含黑名单字段，则处理掉
        if (AddressFilterUtils.containBlack(addressTitle)) {
            addressTitle = entity.getDistrict() + entity.getTownship();
        }

        // 公共厕所 转换 公共设施
        addressTitle = handleReplaceMsg(addressTitle);
        entity.setAddressTitle(addressTitle);

        // 完整地址
        formatAddress = handleReplaceMsg(formatAddress);
        entity.setAddress(formatAddress);

        // 简洁地址
        entity.setSimpleAddress(entity.getCity() + entity.getDistrict() + entity.getTownship());

        entity.setIsFromMapPoint(1);
    }

    /**
     * 处理地址信息替换
     * 猎户座中配置 公共厕所 转换 公共设施
     *
     * @param text
     * @return
     */
    public static String handleReplaceMsg(String text) {
        if (TextUtils.isEmpty(text)) {
            return "";
        }
        SP sp = new SP(ApplicationKt.getContextGlobal());
        String replaceMsgStr = sp.getString("replaceMsg");
        if (!TextUtils.isEmpty(replaceMsgStr)) {
            ReplaceMsgEntity replaceMsgEntity = (ReplaceMsgEntity) JsonUtils.fromJson(replaceMsgStr, ReplaceMsgEntity.class);
            if (null != replaceMsgEntity && !TextUtils.isEmpty(replaceMsgEntity.getSourceMsg())) {
                String sourceMsg = replaceMsgEntity.getSourceMsg();
                String targetMsg = replaceMsgEntity.getTargetMsg();
                if (null != targetMsg) {
                    return text.replace(sourceMsg, targetMsg);
                }
            }
        }
        return text;
    }
}
